/*
 * Copyright (c) 2008 Benoit Bouchez, Nicolas Giard
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.noocodecommit.wicket.stuff.jquery;

import java.util.Iterator;

import org.apache.wicket.RequestCycle;
import org.apache.wicket.ResourceReference;
import org.apache.wicket.behavior.HeaderContributor;
import org.apache.wicket.markup.html.IHeaderContributor;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.WebResource;
import org.apache.wicket.util.resource.AbstractStringResourceStream;
import org.apache.wicket.util.resource.IResourceStream;

import com.noocodecommit.wicket.stuff.jquery.plugin.IJQPluginComponent;
import com.noocodecommit.wicket.stuff.jquery.plugin.JQPlugin;

/**
 * 
 * @author Nicolas Giard
 */
public class JQDocumentReadyResource extends WebResource
{
	private JQCore jqcore;

	/**
	 * @param jqcore
	 */
	public JQDocumentReadyResource(JQCore jqcore)
	{
		this.jqcore = jqcore;
		this.setCacheable(false);
	}

	@Override
	public final IResourceStream getResourceStream()
	{
		return new JavascriptResourceStream(jqcore);
	}

	/**
	 * create a {@link IHeaderContribution header contribution} that will render an autogenerate link to the {@link JavascriptWebResource javascript resource}.
	 * 
	 * @param reference
	 * @return HeaderContributor
	 */
	public static HeaderContributor createHeaderContributor(final ResourceReference reference)
	{
		return new HeaderContributor(new IHeaderContributor()
		{
			public void renderHead(IHeaderResponse response)
			{
				CharSequence url = RequestCycle.get().urlFor(reference, null);

				StringBuffer buffer = new StringBuffer();
				buffer.append("<script type=\"text/javascript\" ");
				buffer.append("src=\"").append(url).append("\">");
				buffer.append("</script>");
				response.renderString(buffer.toString());
			}
		});
	}

	/**
	 * resource stream for streaming javascript content.
	 */
	private static class JavascriptResourceStream extends AbstractStringResourceStream
	{
		private JQCore jqcore;

		public JavascriptResourceStream(JQCore jqcore)
		{
			this.jqcore = jqcore;
		}

		@Override
		protected String getString()
		{
			StringBuffer buffer = new StringBuffer();
			buffer.append("\t$(document).ready(function(){\n");

			// before plugin init scripts
			if (jqcore.getBeforePluginInitScripts().size() > 0)
			{
				buffer.append("\t\t// -----------------------------------\n");
				buffer.append("\t\t// -- JQ4W - BeforePluginInitScripts -\n");
				buffer.append("\t\t// -----------------------------------\n");
			}
			for (int i = 0; i < jqcore.getBeforePluginInitScripts().size(); i++)
			{
				buffer.append("\t\t" + jqcore.getBeforePluginInitScripts().get(i) + "\n");
			}

			// Render jquery function calls for HTML elements with
			// specific behavior
			if (jqcore.getPlugins().size() > 0)
			{
				buffer.append("\t\t// -----------------------------------\n");
				buffer.append("\t\t// -- JQ4W - Plugins Init            -\n");
				buffer.append("\t\t// -----------------------------------\n");
			}
			for (Iterator<String> i = jqcore.getPlugins().keySet().iterator(); i.hasNext();)
			{
				String key = i.next();
				// Choose with plugin init mode
				if (jqcore.getPlugins().get(key).getInitMode() == JQPlugin.PLUGIN_INIT_ONCE)
				{
					if ((jqcore.getPlugins().get(key).getPluginReadyScript() != null) && (jqcore.getPlugins().get(key).getInitOnceSelector() != null))
					{
						buffer.append("\t\t" + jqcore.getPlugins().get(key).getPluginReadyScript() + "\n");
					}
				}
				else if (jqcore.getPlugins().get(key).getInitMode() == JQPlugin.PLUGIN_INIT_EACH_WIDGET)
				{
					for (int j = 0; j < jqcore.getPlugins().get(key).getAttachedComponentsForDocumentReady().size(); j++)
					{
						IJQPluginComponent component = jqcore.getPlugins().get(key).getAttachedComponentsForDocumentReady().get(j);
						if (component.getWidgetReadyScript(false).length() > 0)
						{
							buffer.append("\t\t" + component.getWidgetReadyScript(false) + "\n");
						}
					}
				}
			}

			// after plugin init scripts
			if (jqcore.getAfterPluginInitScripts().size() > 0)
			{
				buffer.append("\t\t// -----------------------------------\n");
				buffer.append("\t\t// -- JQ4W - AfterPluginInitScripts  -\n");
				buffer.append("\t\t// -----------------------------------\n");
			}
			for (int i = 0; i < jqcore.getAfterPluginInitScripts().size(); i++)
			{
				buffer.append("\t\t" + jqcore.getAfterPluginInitScripts().get(i) + "\n");
			}

			buffer.append("\t});\n");

			return buffer.toString();
		}
	}
}